
using UnityEngine;
using System.Collections.Generic;

namespace Battle
{
	public class WalkState : BaseState
	{
		
		public override void OnUpdate(FsmContext context)
		{
			Actor a = context.Actor;
			Actor target = a.DetechTarget();
			if(target!=a.Target)
			{
				a.Target = target;
				Node from = BF.Instance.Map.Index(a.Position);
				Node to = BF.Instance.Map.Index(target.Position);
				BF.Instance.Map.PathFinder.GetPath(from,to,a,ref context.path);
			}
			else
			{
				RemovePath(a.Position,ref context.path);
				if(context.path.Count>0)
				{
					a.Ahead = BF.Instance.Map.Position(context.path[0]) - a.Position;
					a.Position = a.Ahead*a.Speed + a.Position;
				}
			}
		}

		protected void RemovePath(Vector3 pos,ref List<Node> path)
		{
			if(path.Count>0)
			{
				if(Vector3.Distance(pos,BF.Instance.Map.Position(path[0]))<0.1f){
					path.RemoveAt(0);
				}
			}
		}

		public override void EnterState(FsmContext context)
		{
			Actor a = context.Actor;

			if(a.Target!=null)
			{
				Node from = BF.Instance.Map.Index(a.Position);
				Node to = BF.Instance.Map.Index(a.Target.Position);
				BF.Instance.Map.PathFinder.GetPath(from,to,a,ref context.path);
				return;
			}

		}
		
		public override void ExitState(FsmContext context)
		{
			
		}
	}
}